import React, { Component } from 'react';
import { Button, Form, Input, Select, message, Icon, Modal, Radio, Menu, Spin } from 'antd';
import { deepCopy, messages, removeArrayItemByKey, scrollToMyDestination } from 'share/common';
import 'styles/data-center/report/universal-report/single-link-comp.scss';
import withDragDropContext from 'components/with-dnd-context';
import Muuri from 'muuri';

const FormItem = Form.Item;
import SingleAttribute from 'containers/data-center/report/universal-report/components/custom-export-setting/single-attribute';
import debounce from 'lodash.debounce';

@withDragDropContext

class SingleLinkComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentModalId: undefined,
      RadioData: [],
      LinkData: {},
      LinkDataName: {},
      hoverItem: {},
      SearchKeyWord: '',
      list: [],
      mainModalVisible: false,
      radioValue: undefined,
      currentLinkFields: [],
      currentAttributes: [],
      data: undefined,
    };
    this.grid = null;
    this.targetGrid = null;
    this.attrGrid = null;
    this.index = 1000000;
    this.tempCloneMap = {};
    this.disabledMap = [];
    this.handleSearchModalAttributes = debounce(this.handleSearchModalAttributes, 300);
    this.handleDestroyClose = debounce(this.handleDestroyClose, 300);
    this.resizeWindow = debounce(this.resizeWindow, 300);
    this.handleItemMouseOver = debounce(this.handleItemMouseOver, 300);
  }

  componentDidMount() {
    const { onRef, value, allData } = this.props;
    onRef && onRef(this);
    this.setValues(value);
    this.handleAllData(allData);
  }

  componentWillUnmount() {
    // this.grid.destroy();
  }

  componentWillReceiveProps(nextProps) {
    this.setValues(nextProps.value);
    this.handleAllData(nextProps.allData);
  }

  validateFields = () => {
    const { list } = this.state;
    let result = true;
    list.forEach((item, index)=>{
      if (!item.masterColumnId) {
        message.warn(messages('finance-7.key342',{arg1: index+1})/*关联字段 {arg1}，关联字段不能为空*/);
        result = false;
      }
      if (item.reportColumnExportSettingBody && item.reportColumnExportSettingBody.length === 0) {
        message.warn(messages('finance-7.key343',{arg1: index+1})/*关联字段 {arg1}，导出字段不能为空*/);
        result = false;
      }
    })
    return result
  }

  //手动触发 window resize
  resizeWindow = () => {
    let myEvent = new Event('resize');
    window.dispatchEvent(myEvent);
  };

  handleAllData = (allData) => {
    let RadioData = [], LinkData = {}, RadioMap = {}, LinkDataName = {};
    allData.forEach((category)=>{
      const { reportColumnDTOList, reportColumnCustomizedDTOList } = category.masterReport;
      LinkData[category.basicInfoReport.id] = category.basicInfoReport.reportColumnDTOList;
      LinkDataName[category.basicInfoReport.id] = category.basicInfoReport.reportName;
      RadioData.push({
        label: category.basicInfoReport.reportName,
        radios: reportColumnDTOList || reportColumnCustomizedDTOList
      })
      let radios = reportColumnDTOList || reportColumnCustomizedDTOList;
      radios.forEach((radio)=>{
        RadioMap[radio.id] = radio;
      })
    });
    this.setState({RadioData, LinkData, RadioMap, LinkDataName})
  }

  initMuuri = (List) => {
    if (this.grid) {
      let data = this.getMuuriItemKeyArray(this.grid);
      List.forEach((item)=>{
        let target = data.find(id => item.uniqueId === id);
        if (target === undefined) {
          let items = this.grid.add(document.getElementById(item.uniqueId), { index: -1, active: false });
          this.grid.show(items);
        }
      })
      return
    }
    this.grid = new Muuri('.field-container');
  }

  initAttrMuuri = (List) => {
    if (this.attrGrid) {
      let dataArray = this.getMuuriItemKeyArray(this.attrGrid);
      List.forEach((item)=>{
        let target = dataArray.find(id => `${item.id}` === id.toString());
        if (target === undefined) {
          let items = this.attrGrid.add(document.getElementById(`${item.id}-list`), { index: -1, active: false });
          this.attrGrid.show(items);
        }
      })
      return
    }
    this.attrGrid = new Muuri('.muuri-list-box', {})
  }

  initTargetMuuri = (List) => {
    if (this.targetGrid) {
      let dataArray = this.getMuuriItemKeyArray(this.targetGrid);
      List.forEach((item)=>{
        let target = dataArray.find(slaveColumnId => item.slaveColumnId === slaveColumnId);
        if (target === undefined) {
          let items = this.targetGrid.add(document.getElementById(`${item.slaveColumnId}-current`), { index: -1, active: false });
          this.targetGrid.show(items);
        }
      })
      return
    }
    this.targetGrid = new Muuri('.link-list', {
      dragEnabled: true,
      dragContainer: document.getElementById('custom-report-drag-container'),
      dragSort: ()=>{
        return [this.targetGrid]
      },
      dragStartPredicate: {
        distance: 5,
        delay: 0,
      },
      dragPlaceholder: {
        enabled: true,
      },
      itemPlaceholderClass: 'muuri-item-placeholder-attr',
      itemReleasingClass: 'muuri-item-releasing-attr',
      itemDraggingClass: 'muuri-item-dragging-attr'
    }).on('dragReleaseEnd', (data)=>{

    })
  }

  getMuuriItemKeyArray = (grid) => {
    let itemIds = grid.getItems()
      .map((item) => {
        return item.getElement().getAttribute('data-id');
      });
    return itemIds;
  };

  setValues = value => {
    value.forEach((item, index)=>{
      if (!value[index].uniqueId) {
        value[index].uniqueId = `${item.masterColumnId}-${item.basicInfoReportId}`;
      }
    })
    this.setState({list: value}, ()=>{
      if (value && value.length > 0)
        this.initMuuri(value)
    })
  }

  onChange = () => {
    const { onChange } = this.props;
    onChange && onChange(this.state.list);
  };

  onNameChange = (value, index) => {
    const { list } = this.state;
    list[index].columnDisplayName = value.columnDisplayName.name;
    list[index].i18n.columnDisplayName = value.columnDisplayName.i18n;
    this.setState({list}, this.onChange)
  }

  onTypeChange = (value, index) => {
    const { list } = this.state;
    list[index].dataType = value.dataType;
    this.setState({list}, this.onChange)
  }

  addSingleField = () => {
    const { list } = this.state;
    list.push({uniqueId: `${++this.index}`, masterColumnId: '', basicInfoReportId: '', reportColumnExportSettingBody: []});
    this.setState({list}, ()=>{
      this.onChange();
      let items = this.grid.add(document.getElementById(list[list.length - 1].uniqueId), { index: -1, active: false });
      this.grid.show(items);
    });
  }

  deleteSingleItem = (e, item) => {
    e.preventDefault();
    if (item.masterColumnId || item.reportColumnExportSettingBody.length) {
      Modal.confirm({
        title: messages('common.info')/*提示*/,
        content: messages('finance-7.key344')/*当前关联字段已设置，确定删除？*/,
        onOk: () => {
          this.handleRemoveSingle(item);
        }
      });
    } else {
      this.handleRemoveSingle(item);
    }
  }

  handleRemoveSingle = (item) => {
    let list = removeArrayItemByKey(this.state.list, item, 'uniqueId');
    let deleteItem = this.grid.getItems()
      .filter((filterItem) => {
        return filterItem.getElement().getAttribute('data-id') === item.uniqueId
      });
    this.grid.remove(deleteItem, { removeElements: false });
    this.setState({list}, this.onChange)
  }

  onFocus = (index) => {
    this.refs[`chooserBlur-${index}`].focus();
    this.setState({
      mainModalVisible: true,
      currentIndex: index,
      openValue: this.state.list[index].masterColumnId,
      radioValue: this.state.list[index].masterColumnId
    });
  }

  openLinkModal = (index) => {
    let currentLinkFields = deepCopy(this.state.list[index].reportColumnExportSettingBody);
    this.setState({
      currentModalId: this.state.list[index].basicInfoReportId,
      linkModalVisible: true,
      currentIndex: index,
      currentLinkFields
    }, ()=>{
      this.initTargetMuuri(currentLinkFields);
      this.initAttrMuuri(this.state.LinkData[this.state.list[index].basicInfoReportId])
    });
  }

  handleMainModalClose = () => {
    this.setState({mainModalVisible: false, currentIndex: -1, openValue: undefined});
  }

  handleModalClose = () => {
    this.setState({linkModalVisible: false}, ()=>{
      this.handleDestroyClose();
    });
  }

  handleDestroyClose = () => {
    this.attrGrid.remove(this.attrGrid.getItems(), { removeElements: false });
    this.targetGrid.remove(this.targetGrid.getItems(), { removeElements: false });
    this.setState({currentLinkFields: [], currentModalId: undefined});
  }

  onMainChange = (e) => {
    this.setState({radioValue: e.target.value})
  }

  handleSelectMainLink = () => {
    const { radioValue, currentIndex, list, RadioMap } = this.state;
    let haveData = !!list[currentIndex].reportColumnExportSettingBody.length;
    // let originTargetId = RadioMap[list[currentIndex].masterColumnId] && RadioMap[list[currentIndex].masterColumnId].targetReportId,
    //   newTargetId = RadioMap[radioValue].targetReportId;
    let originTargetId = list[currentIndex].masterColumnId,
      newTargetId = radioValue;
    // if (originTargetId !== undefined && originTargetId !== newTargetId && haveData) {
    if (originTargetId !== undefined && originTargetId !== newTargetId && haveData) {
        Modal.confirm({
        title: messages('common.info')/*提示*/,
        content: messages('finance-7.key345')/*切换关联字段会清空导出字段，确定切换？*/,
        onOk: () => {
          this.handleChangeMainLinkField({ list, currentIndex, radioValue, RadioMap }, true);
        }
      });
    } else {
      this.handleChangeMainLinkField({ list, currentIndex, radioValue, RadioMap });
    }
  }

  handleChangeMainLinkField = ({ list, currentIndex, radioValue, RadioMap }, needClear = false) => {
    list[currentIndex].masterColumnId = radioValue;
    list[currentIndex].basicInfoReportId = RadioMap[radioValue].targetReportId;
    list[currentIndex].masterColumnDisplayName = RadioMap[radioValue].columnDisplayName;
    if (needClear)
      list[currentIndex].reportColumnExportSettingBody = [];
    this.setState({list, radioValue: undefined, openValue: undefined}, ()=>{
      this.onChange();
      this.handleMainModalClose();
      this.resizeWindow();
    })
  }

  handleSearchModalAttributes = (e) => {
    this.setState({SearchKeyWord: e || ''})
    this.attrGrid.filter((item)=>{
      return item.getElement().children[0].innerText.indexOf(e) !== -1;
    })
  }

  modalSearchOnChange = (e) => {
    e.persist();
    this.handleSearchModalAttributes(e.target.value)
  }

  addAttributeToTarget = (e, item) => {
    e.stopPropagation();
    e.preventDefault();
    const { currentLinkFields } = this.state;
    currentLinkFields.push({
      slaveColumnId: item.id,
      slaveColumnDisplayName: item.columnDisplayName
    });
    this.setState({currentLinkFields}, ()=>{
      let items = this.targetGrid.add(document.getElementById(`${item.id}-current`), { index: -1, active: false });
      this.targetGrid.show(items);
    })
  }

  changeItemName = (newName, item) => {
    const { currentLinkFields } = this.state;
    currentLinkFields.forEach((field)=>{
      if (field.slaveColumnId === item.slaveColumnId) {
        field.slaveColumnDisplayName = newName;
      }
    })
    this.setState({currentLinkFields}, this.resizeWindow);
  }

  deleteFieldItem = (widget, out, index) => {
    if (out) {
      const {list} = this.state;
      let reportColumnExportSettingBody = removeArrayItemByKey(list[index].reportColumnExportSettingBody, widget, 'slaveColumnId');
      list[index].reportColumnExportSettingBody = reportColumnExportSettingBody;
      this.setState({list}, ()=>{
        this.onChange();
        this.resizeWindow();
      });
    } else {
      let currentLinkFields = removeArrayItemByKey(this.state.currentLinkFields, widget, 'slaveColumnId');
      let deleteItem = this.targetGrid.getItems()
        .filter((filterItem) => {
          return filterItem.getElement().getAttribute('data-id') === (widget.slaveColumnId).toString()
        });
      this.targetGrid.remove(deleteItem, { removeElements: false });
      this.setState({currentLinkFields, hoverItem: {}})
    }
  }

  handleSelectLink = () => {
    const { currentLinkFields, currentIndex, list } = this.state;
    let sorted = [], data = this.getMuuriItemKeyArray(this.targetGrid);
    data.forEach((id)=>{
      currentLinkFields.forEach((field)=>{
        if (id === field.slaveColumnId)
          sorted.push(field)
      })
    })
    list[currentIndex].reportColumnExportSettingBody = sorted;
    this.setState({list, currentIndex: -1}, ()=>{
      this.handleModalClose();
      this.onChange();
      this.resizeWindow();
    })
  }

  handleItemMouseOver = (item) => {
    this.setState({hoverItem: item});
  }

  handleOnItemClick = (e, item, disabledItem) => {
    // let y = document.getElementById(`custom-modal-data-${item.reportColumnId || item.id}`).offsetTop;
    // scrollToMyDestination(this.dataListBoxRef, y);
  }

  handleItemMouseLeave = () => {
    this.handleItemMouseOver.cancel();
    this.setState({hoverItem: {}});
  }

  render() {
    const { list, mainModalVisible, radioValue, linkModalVisible, currentLinkFields,
      currentModalId, RadioData, openValue, LinkData, LinkDataName, hoverItem } = this.state;
    const disabledRadios = list.map(item=>item.masterColumnId).filter(item=>item !== openValue);
    return (
      <div className='single-field-component'>
        <FormItem required label={messages('finance-7.key346')/*关联字段*/}>
          <Button type={'primary'} onClick={this.addSingleField}>{messages('finance-7.key347')/*添加关联字段*/}</Button>
        </FormItem>
        <div className="field-container">
          {list.map((item, index)=>
            <div className={'single-field-item'} key={item.uniqueId} data-id={item.uniqueId} id={item.uniqueId}>
              <div className='single-link-box'>
                <div className="title-and-delete">
                  <div className="title">{messages('finance-7.key346')/*关联字段*/} {index + 1}</div>
                  <div onClick={(e)=>{this.deleteSingleItem(e, item)}}><Icon type="delete" /></div>
                </div>
                <Form>
                  <Form.Item required label={messages('finance-7.key346')/*关联字段*/}>
                    <Select
                      placeholder={messages('common.select')/*请选择*/}
                      labelInValue
                      value={item.masterColumnId ? [{ label: item.masterColumnDisplayName, key: item.masterColumnId }] : []}
                      onFocus={()=>{this.onFocus(index)}}
                      dropdownStyle={{display: "none"}}
                    />
                    <div>
                      <input
                        ref={`chooserBlur-${index}`}
                        style={{ opacity: 0, position: 'fixed', width: 0, height: 0, zIndex: -1 }}
                      />
                    </div>
                  </Form.Item>
                  <Form.Item required label={messages('finance-7.key348')/*导出字段*/}>
                    {item.masterColumnId ?
                      <span className={'add-style'} onClick={()=>{this.openLinkModal(index)}}><Icon type="plus" /> {messages('finance-7.key349')/*添加导出字段*/}</span> :
                      <span className={'tip-style'}>{messages('finance-7.key350')/*确定关联字段后，可选择导出字段*/}</span>
                    }
                    <div className='fields-area'>
                      {
                        item.reportColumnExportSettingBody.map((field)=>{
                          return (
                            <SingleAttribute
                              disabled
                              unique={'display'}
                              key={field.slaveColumnId}
                              widget={field}
                              index={index}
                              deleteItem={(widget)=>{this.deleteFieldItem(widget, true, index)}}
                            />
                          )
                        })
                      }
                    </div>
                  </Form.Item>
                </Form>
              </div>
            </div>
          )}
        </div>
        <Modal
          maskClosable={false}
          className={'choose-main-link-field-modal'}
          width={760}
          visible={mainModalVisible}
          title={messages('finance-7.key346')/*关联字段*/}
          onCancel={this.handleMainModalClose}
          onOk={this.handleSelectMainLink}
        >
          <Radio.Group value={radioValue} onChange={this.onMainChange}>
            {RadioData.map((category)=>{
              return (<div className={'single-category'}>
                <p className='category-radio-name'>{category.label}</p>
                {category.radios.map((radio, index)=>{
                  return (
                    <Radio
                      value={radio.id}
                      disabled={(disabledRadios.indexOf(radio.id) !== -1)}
                    >
                      {radio.columnDisplayName}
                    </Radio>
                  )
                })}
              </div>)
            })}

          </Radio.Group>
        </Modal>
        <Modal
          bodyStyle={{padding: '10px 20px'}}
          maskClosable={false}
          className={'choose-link-field-modal'}
          width={760}
          visible={linkModalVisible}
          title={messages('finance-7.key348')/*导出字段*/}
          onCancel={this.handleModalClose}
          onOk={this.handleSelectLink}
        >
          <div className={'custom-report-data-content'}>
            <div className="link-title">{messages('finance-7.key348')/*导出字段*/}</div>
            <div className="link-list">
              {currentLinkFields.map((field, index)=>{
                return (
                  <SingleAttribute
                    unique={'current'}
                    key={field.slaveColumnId}
                    widget={field}
                    index={index}
                    onItemMouseOver={this.handleItemMouseOver}
                    onItemMouseLeave={this.handleItemMouseLeave}
                    onItemClick={this.handleOnItemClick}
                    onSaveI18n={this.changeItemName}
                    deleteItem={this.deleteFieldItem}
                  />
                )
              })}
            </div>
            {currentLinkFields.length === 0 ? <div className='place-holder'>{messages('finance-7.key351')/*点击下方字段进行添加*/}</div> : null}
          </div>
          <div className="title-line">
            <div>
              <span className={'title'}>{messages('finance-7.key352')/*附表字段*/}</span>
              <span className={'list-title'}>{LinkDataName[currentModalId]}</span>
            </div>
            <div className={`input-search`}>
              <Input.Search
                placeholder={messages('basic-10.key134')/*搜索字段名*/}
                style={{ width: 240 }}
                onChange={this.modalSearchOnChange}
                onSearch={this.handleSearchModalAttributes}
              />
            </div>
          </div>
          <div className="attr-list-box">
            <div className="muuri-list-box">
              {LinkData && Object.keys(LinkData).length !== 0 && currentModalId !== undefined && LinkData[currentModalId].map((field, index) => {
                return (
                  <SingleAttribute
                    disabled
                    unique={'list'}
                    currentSelect={currentLinkFields}
                    onItemClick={(e)=>{this.addAttributeToTarget(e, field)}}
                    key={field.id}
                    widget={field}
                    index={index}
                    hoverItem={hoverItem}
                  />
                );
              })}
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

SingleLinkComp.propTypes = {};

export default SingleLinkComp;
